package com.zr.service;

import com.zr.dto.MenuDTO;
import com.zr.entity.Menu;
import com.zr.entity.Staff;
import com.zr.enums.CoreExceptionEnum;
import com.zr.exception.ServiceException;
import com.zr.interfaces.IStaffService;
import com.zr.mapper.StaffMapper;
import com.zr.pojo.Result;
import com.zr.utils.BeanHelper;
import com.zr.vo.StaffVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: peterChen
 * @date: 2019/11/14 20:48
 * @description: com.zr.service
 * @version: 1.0
 */
@Slf4j
@Service
public class StaffService implements IStaffService {
    @Autowired
    private StaffMapper staffMapper;

    /**
     * 单个添加员工信息
     * @param staffVO
     */
    @Override
    public void addStaff(StaffVO staffVO) {
        Staff staff = BeanHelper.copyProperties(staffVO, Staff.class);
        //判断该员工是否已添加
        int count = staffMapper.selectCount(staff);
        if(count == 1){
            log.error("该员工信息已添加！");
            throw new ServiceException(CoreExceptionEnum.DATA_ALREADY_EXISTS);
        }
        int i = staffMapper.insertSelective(staff);
        if(i == 0){
            log.error("员工添加失败");
            throw new ServiceException(CoreExceptionEnum.INSERT_OPERATION_FAIL);
        }
    }


    /**
     * 批量导入excel表中员工信息
     * @param list
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void add(List<String[]> list) {
        if (list != null && list.size() > 0) {
            List<StaffVO> staffVOList = new ArrayList<>();
            for (String[] strings : list) {
                StaffVO staffVO =
                        new StaffVO(strings[0], strings[1], new Date(strings[2]), (strings[3].equals("1") ? 1 : 2),
                                strings[4], (strings[5].equals("1")? 1 : 2), (strings[6].equals("1")? 1 : 2),
                                Integer.parseInt(strings[7]), Integer.parseInt(strings[8]),
                                new Date(strings[9]), strings[10], strings[11], strings[12], strings[13], strings[14],
                                Integer.parseInt(strings[15]), strings[16]);
                staffVOList.add(staffVO);
            }
            //转换为实体类
            List<Staff> staffList = BeanHelper.copyWithCollection(staffVOList, Staff.class);

            //方案一：直接批量导入，不需要判断添加的员工是否已添加
            //批量添加
            //if (!CollectionUtils.isEmpty(staffList)) {
            //    int count = staffMapper.insertStaffList(staffList);
            //    log.info("count:" + count);
            //    if (count != staffList.size()) {
            //        log.error("员工批量导入失败");
            //        throw new ServiceException(CoreExceptionEnum.INSERT_OPERATION_FAIL);
            //    }
            //}
            //方案二：业务层进行查询判断，已添加则进行更新，未添加则进行添加
            //批量添加
            ArrayList<Staff> staffExists = new ArrayList<>();
            staffList.stream().forEach(staff -> {
                Staff sta = staffMapper.selectByIdentificationNum(staff.getIdentificationNum());
                if(sta != null){
                    log.error("请检查传入员工信息是否已存在");
                    throw new ServiceException(CoreExceptionEnum.INSERT_OPERATIONS_FAIL);
                }
            });

            int count = staffMapper.insertStaffList(staffList);
            if (count != staffList.size()) {
                log.error("员工批量导入失败");
                throw new ServiceException(CoreExceptionEnum.INSERT_OPERATION_FAIL);
            }


        }


    }

    /**
     * 将传入的员工信息进行转换
     * @param staffVO
     * @return
     */
    private Staff getStaff(StaffVO staffVO) {
        Staff staff = BeanHelper.copyProperties(staffVO, Staff.class);
        staff.setSex(staffVO.getSex().equals("男")? 0 : 1);
        staff.setBusinessDept(staffVO.getBusinessDept().equals("是")? 0 : 1);
        staff.setDeliveryDept(staffVO.getDeliveryDept().equals("是")? 0 : 1);
        //staff.setStatus(staffVO.getStatus().equals("待审批")? 0 : 1);
        return staff;
    }

    /**
     * 获取所有菜单（含子菜单）
     * @return
     */
    @Override
    public List<MenuDTO> getAllMenus(Integer roleId) {
        List<Menu> menus = staffMapper.getParentMenus(roleId);
        if(CollectionUtils.isEmpty(menus)){
            throw new ServiceException(CoreExceptionEnum.UNAUTHORIZED);
        }
        List<MenuDTO> menuDTOS = BeanHelper.copyWithCollection(menus, MenuDTO.class);
        //TODO 待实现递归查询子菜单(递归会降低查询效率)
        menuDTOS.stream()
                .forEach(menuDTO -> {
                    List<Menu> childMenus = staffMapper.getChildMenusByParentId(menuDTO.getId());
                    if(childMenus != null && childMenus.size() > 0){
                        menuDTO.setChildren(BeanHelper.copyWithCollection(childMenus,MenuDTO.class));
                    }
                });
        return menuDTOS;
    }

}
